package com.snio.dingding.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.snio.dingding.service.IActivitiModelService;

/**
 * @copyright:南京中程智慧科技有限公司
 * @createTime:2017年2月13日-上午10:45:48
 * @Version:1.0
 * @author:shazhengbo
 * @description: 工作流业务操作实现类
 */

public class ActivitiModelServiceImpl implements IActivitiModelService {

	@Autowired
	private RepositoryService repositoryService;

	@Autowired
	private RuntimeService runtimeService;

	@Override
	public List<Model> getModelList() {
		return repositoryService.createModelQuery().orderByCreateTime().desc().list();
	}

	@Override
	public Map<String, Object> delModel(String modelId) {
		Map<String, Object> map = new HashMap<>();
		try {
			repositoryService.deleteModel(modelId);
			map.put("result", true);
			map.put("msg", "删除成功!");
		} catch (Exception e) {
			map.put("result", false);
			map.put("msg", "删除失败!");
			e.printStackTrace();
		}
		return map;
	}

	@Override
	public Map<String, Object> deploymentModel(String modelId) {
		Map<String, Object> map = new HashMap<>();
		try {
			Model modelData = repositoryService.getModel(modelId);
			ObjectNode modelNode = (ObjectNode) new ObjectMapper()
					.readTree(repositoryService.getModelEditorSource(modelData.getId()));
			byte[] bpmnBytes = null;
			BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
			bpmnBytes = new BpmnXMLConverter().convertToXML(model);
			String processName = modelData.getName() + ".bpmn20.xml";
			Deployment deployment = repositoryService.createDeployment().name(modelData.getName())
					.addString(processName, new String(bpmnBytes, "utf-8")).deploy();
			map.put("result", true);
			map.put("msg", "部署成功!");
		} catch (Exception e) {
			map.put("result", false);
			map.put("msg", "部署失败!");
			e.printStackTrace();
		}
		return map;
	}

	@Override
	public List<Deployment> deploymentList() {
		return repositoryService.createDeploymentQuery().orderByDeploymenTime().asc().list();
	}

	@Override
	public ProcessInstance startprocessInstanceByKey(String key) {
		ProcessInstance processInstance=null;
		try {
			 processInstance = runtimeService.startProcessInstanceByKey(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return processInstance;
	}

}
